Hash consing

In computer science, particularly in functional programming, hash consing is a technique used to share values that are structurally equal. The term hash consing originates from implementations of Lisp[1] that attempt to reuse cons cells that have been constructed before, avoiding the penalty of memory allocation. Hash consing is most commonly implemented with hash tables storing weak references that may be garbage-collected when the data stored therein contains no references from outside the table.[2][3] Hash consing has been shown to give dramatic performance improvements—both space and time—for symbolic and dynamic programming algorithms.

In other communities a similar idea is known as the Flyweight pattern. When applied to strings this technique is also known as string interning.

Contents

Examples

Scheme

Simple, not very efficient, but suitable for demonstration of the concept implementation of a memoizer by means of hash table and weak references in Scheme:

;; weak hashes
;;
;; memoizer factory: for given (side-effect-free) procedure,
;; return a procedure which does the same memoizing some of results
;; in the sense of equal? on the whole list of args
;;
 

References

  1. ^ Goto, Eiichi (1974). Monocopy and associative algorithms in extended Lisp. Tokyo: University of Tokyo Technical Report TR 74-03. 
  2. ^ Allen, John (1978). Anatomy of Lisp. McGraw Hill. ISBN 007001115X. 
  3. ^ Fillâtre, Jean-Christophe; Conchon, Sylvain (2006). "Type-Safe Modular Hash-Consing". Workshop on ML. ACM. 

Further reading